package org.hyperzsoft.frags;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.hyperzsoft.UserTask;
import org.hyperzsoft.utilities;
import org.hyperzsoft.com.R;
import org.hyperzsoft.one.Team;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//@SuppressWarnings("unused")
public class GetDataFragment extends Fragment {	
	private GetDataTask mGetData;
	private Activity mAttachedActivity;
	
	
	private void standingsImport() {
        if (mGetData == null || mGetData.getStatus() == UserTask.Status.FINISHED) {
        	mGetData = (GetDataTask) new GetDataTask().execute();
        } else {
            utilities.showToast(mAttachedActivity, R.string.error_import_in_progress);
        }
    }
	
	// First - [Created]
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		//store the activity this fragment is attached to
		mAttachedActivity = activity;
	}
	
	// Second
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	// Third
	public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)  {
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	
	// Fourth
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		standingsImport();
	}
	
	// Fifth [Started]
	public void onStart() {
		super.onStart();
	}
	
	// Sixth [Resumed]
	public void onResume() {
		super.onResume();
	}
	
	// Seventh [Paused]
	public void onPause() {
		super.onPause();
	}
	
	// Eighth [Stopped]
	public void onStop() {
		super.onStop();
	}
	
	// Ninth [Destroyed]
	public void onDestroyView() {
		super.onDestroyView();
	}
	
	// Tenth 
	public void onDestroy() {
		super.onDestroy();
	}
	
	// Eleventh
	public void onDetach() {
		super.onDetach();
	}
	
	private void onCancelGetData() {
        if (mGetData != null && mGetData.getStatus() == UserTask.Status.RUNNING) {
        	mGetData.cancel(true);
        	mGetData = null;
        }
    }
    
	private class GetDataTask extends UserTask<String, Integer, Void> {
    	@Override
        public void onPreExecute() {
    		((ProgressBar) mAttachedActivity.findViewById(R.id.progress)).setIndeterminate(true);
    		
            final View cancelButton = mAttachedActivity.findViewById(R.id.button_cancel);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	onCancelGetData();
                }
            });
    	}
    	
    	@Override
        public void onCancelled() {
    		
    	}
    	
    	@Override
    	public Void doInBackground(String... params) {
			long timing;
			ArrayList<Team> teams = new ArrayList<Team>();
			Calendar cal = Calendar.getInstance();
			
			timing = cal.getTimeInMillis();
			
			cal.roll(Calendar.DATE, true);
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			
			Document doc = utilities.getDocument("http://www.nhl.com/ice/standings.htm", 
					"date", sdf.format(cal.getTime()), "season", 
					utilities.getSeasonValue(), "type", "LEA");
			
			Element standings = doc.body().select("tbody").get(2);
			
			mAttachedActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					((TextView) mAttachedActivity.findViewById(R.id.label_import)).setText(
                    	"Get & Parse of Standings complete, Starting team data build...");
				}
			});
			
			for (Element teamRow : standings.select("tr")) {
				if (isCancelled()) return null;
				final Team currTeam = new Team();
				currTeam.BuildTeamFromNode(teamRow);
				teams.add(currTeam);
				mAttachedActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						((TextView) mAttachedActivity.findViewById(R.id.label_import)).setText(
								"Data built for " + currTeam.getFullName() + ", moving to next team...");
					}
				});
			}
			
			cal = Calendar.getInstance();
			final long finalTiming = cal.getTimeInMillis() - timing;
			
			mAttachedActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(mAttachedActivity, "Built standings in " + finalTiming + " msecs", Toast.LENGTH_LONG).show();
				}
			});
			
    		return null;
    	}
    	
    	@Override
        public void onPostExecute(Void result) {
    		
    	}
    }
}